<!--增删改查通用列表组件-->
<template>

  <a-row :gutter="10">
      <a-col :span="6" v-for="item in config.item">
        <a-input
            v-model:value="formData[item.name]"
            :placeholder="item.placeholder"
            v-if="item.type === 'input'"
        />
        <a-select style="width: 100%"
            v-if="item.type === 'select'"
            :placeholder="item.placeholder"
            v-model:value="formData[item.name]"
            :options="item.options"
        >
        </a-select>
      </a-col>

  <a-col :span="6" style="text-align: left">
    <a-button type="primary" @click="onQuery">查询</a-button>
    <a-button style="margin-left: 10px;" v-if="config.addBtn" type="primary" @click="config.addBtn">新增</a-button>
    <a-button style="margin-left: 10px;" v-if="config.exporBtn" type="primary" @click="exporBtn">导出</a-button></a-col>

</a-row>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, toRefs, onMounted,inject } from "vue";
import axios from "axios";




export default defineComponent({
  props: ["config"],
  emits: ["on-query","on-add"],
  setup(props, context) {
    const formData = reactive({});





    onMounted(() => {
      props.config.item.forEach((item) => {
        formData[item.name] = item.defaultValue ? item.defaultValue : undefined;
      });
    });

    const exporBtn = () => {
      let token:any = localStorage.getItem("token")




      axios(
      {
         method: "get",
         url: "api/user/export",
         responseType: "blob", // 表明返回服务器返回的数据类型
          headers: {
           "Authorization": token?token:"no-token",
           "Content-Type": "application/vnd.ms-excel",
      },
      }
      ).then(res=>{
        console.log(res)
        // 处理返回的文件流
        let blob = new Blob([res.data] );
        //获取fileName,截取content-disposition的filename；按=分割，取最后一个
        const fileName = decodeURI("sad.xlsx");
        let downloadElement = document.createElement("a");
        let href = window.URL.createObjectURL(blob); //创建下载的链接
        downloadElement.href = href;
        downloadElement.download = fileName; //下载后文件名
        document.body.appendChild(downloadElement);
        downloadElement.click(); //点击下载
        document.body.removeChild(downloadElement); //下载完成移除元素
        window.URL.revokeObjectURL(href); //释放blob


      })

    }


    const onQuery = () => {
      //处理值，把不为undefined的值传出去
      let obj = {};
      for (let key in formData) {
        if (formData[key] !== undefined) {
          obj[key] = formData[key];
        }
      }
      context.emit("on-query", obj);
    };
    return {
      formData,
      onQuery,
      exporBtn

    };
  },
});
</script>
